/**
 * Copyright (c) 2016-2019 人人开源 All rights reserved.
 * <p>
 * https://www.renren.io
 * <p>
 * 版权所有，侵权必究！
 */

package com.sankuai.demo.utils;

import com.google.gson.Gson;
import org.springframework.dao.DataAccessException;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.connection.RedisStringCommands;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.data.redis.core.types.Expiration;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * Redis工具类
 *
 * @author Mark sunlightcs@gmail.com
 */
@Component
public class RedisUtils {

    @Resource
    private RedisTemplate redisTemplate;

    @Resource
    private ValueOperations valueOperations;

//    @Resource
//    private HashOperations<String, String, Object> hashOperations;
//
//    @Resource
//    private ListOperations<String, Object> listOperations;
//
//    @Resource
//    private SetOperations<String, Object> setOperations;
//
//    @Resource
//    private ZSetOperations<String, Object> zSetOperations;
    /**
     * 默认过期时长，单位：秒
     */
    public final static long DEFAULT_EXPIRE = 60 * 60 * 24;
    /**
     * 不设置过期时长
     */
    public final static long NOT_EXPIRE = -1;

    private final static Gson gson = new Gson();

    public void set(String key, Object value, long expire) {
        valueOperations.set(key, toJson(value));
        if (expire != NOT_EXPIRE) {
            redisTemplate.expire(key, expire, TimeUnit.SECONDS);
        }
    }

    public void set(String key, Object value) {
        set(key, value, DEFAULT_EXPIRE);
    }

//    public <T> T get(String key, Class<T> clazz, long expire) {
//        String value = valueOperations.get(key);
//        if (expire != NOT_EXPIRE) {
//            redisTemplate.expire(key, expire, TimeUnit.SECONDS);
//        }
//        return value == null ? null : fromJson(value, clazz);
//    }

//    public <T> T get(String key, Class<T> clazz) {
//        return get(key, clazz, NOT_EXPIRE);
//    }

//    public String get(String key, long expire) {
//        String value = valueOperations.get(key);
//        if (expire != NOT_EXPIRE) {
//            redisTemplate.expire(key, expire, TimeUnit.SECONDS);
//        }
//        return value;
//    }

//    public String get(String key) {
//        return get(key, NOT_EXPIRE);
//    }

    public void delete(String key) {
        redisTemplate.delete(key);
    }

    /**
     * Object转成JSON数据
     */
    private String toJson(Object object) {
        if (object instanceof Integer || object instanceof Long || object instanceof Float ||
                object instanceof Double || object instanceof Boolean || object instanceof String) {
            return String.valueOf(object);
        }
        return gson.toJson(object);
    }

    /**
     * JSON数据，转成Object
     */
    private <T> T fromJson(String json, Class<T> clazz) {
        return gson.fromJson(json, clazz);
    }

    //批量添加
    public void batchSet(Map<String, String> map) {
        redisTemplate.opsForValue().multiSet(map);
    }

    //批量获取
    public List<Object> batchGet(List<String> list) {
        List<Object> objectList = redisTemplate.opsForValue().multiGet(list);
        return objectList;
    }

    //批量添加 并且设置失效时间
    public void batchSetOrExpire(Map<String, String> map, Long seconds) {
        RedisSerializer<String> serializer = redisTemplate.getStringSerializer();
        redisTemplate.executePipelined(new RedisCallback<String>() {
            @Override
            public String doInRedis(RedisConnection connection) throws DataAccessException {
                map.forEach((key, value) -> {
                    connection.set(serializer.serialize(key), serializer.serialize(value),
                            Expiration.seconds(seconds), RedisStringCommands.SetOption.UPSERT);
                });
                return null;
            }
        }, serializer);
    }

}
